package com.sdkj.dspservice.modules.report.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.controller.BaseController;
import com.sdkj.dspservice.common.config.Global;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.common.utils.IdGen;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.modules.report.entity.TableConfig;
import com.sdkj.dspservice.modules.report.entity.TableConfigColumn;
import com.sdkj.dspservice.modules.report.entity.tem.QueryColumn;
import com.sdkj.dspservice.modules.report.entity.tem.TableInfo;
import com.sdkj.dspservice.modules.report.service.SourceService;
import com.sdkj.dspservice.modules.report.service.TableConfigColumnService;
import com.sdkj.dspservice.modules.report.service.TableConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表配置控制器
 * @author tm
 */
@Api(value = "表配置", tags = "表配置控制器")
@ApiResponses(@ApiResponse(code = 404, message = "表配置不存在"))
@Slf4j
@RestController
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/report/tableConfig")
public class TableConfigController extends BaseController {

    @Autowired
    private TableConfigService tableConfigService;
    @Autowired
    private TableConfigColumnService tableConfigColumnService;
    @Autowired
    private SourceService sourceService;

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取详情")
    @GetMapping(value = "get")
    public AntdProResult get(String id) {
        AntdProResult result = new AntdProResult();
        TableConfig tableConfig = tableConfigService.getById(id);
        result.success(tableConfig);
        return result;
    }

    /**
     * 获取列表
     *
     * @param tableConfig
     * @return
     */
    @ApiOperation(value = "获取列表")
    @GetMapping(value = "list")
    public AntdProResult list(TableConfig tableConfig) {
        AntdProResult result = new AntdProResult();
        List<TableConfig> tableConfigList = tableConfigService.listLink(tableConfig.makeQueryWrapper(new QueryWrapper<>(tableConfig)));
        result.success(tableConfigList);
        return result;
    }

    /**
     * 保存（添加或修改）
     *
     * @param tableConfig
     * @return
     */
    @ApiOperation(value = "保存（添加或修改）")
    @PostMapping(value = "save")
    public AntdProResult save(@Valid @RequestBody TableConfig tableConfig) {
        AntdProResult result = new AntdProResult();
        tableConfigService.saveOrUpdate(tableConfig);
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "remove")
    public AntdProResult delete(String id) {
        AntdProResult result = new AntdProResult();
        tableConfigService.removeById(id);
        return result;
    }

    /**
     * 获取select列表
     *
     * @param tableConfig
     * @return
     */
    @ApiOperation(value = "获取select列表")
    @GetMapping(value = "listForSelect")
    public AntdProResult listForSelect(TableConfig tableConfig) {
        AntdProResult result = new AntdProResult();
        List<TableConfig> tableConfigList = tableConfigService.list(tableConfig);
        // 转换为{label:xxx,value:xxx}
        List<Map<String, Object>> mapList = new ArrayList<>();
        for(TableConfig r : tableConfigList){
            Map<String, Object> map = new HashMap<>(2);
            map.put("label", r.getName());
            map.put("value", r.getId());
            mapList.add(map);
        }
        result.success(mapList);
        return result;
    }

    /**
     * 获取columnList
     *
     * @param tableConfig
     * @return
     */
    @ApiOperation(value = "获取字段列表")
    @RequestMapping(value = "getColumnList")
    public AntdProResult getColumnList(@RequestBody TableConfig tableConfig) {
        AntdProResult result = new AntdProResult();
        List<TableConfigColumn> resultList = new ArrayList<>();
        // id不为空，拉取report_table_config_column表数据
        if(StringUtils.isNotBlank(tableConfig.getId())){
            TableConfigColumn searchTableConfigColumn = new TableConfigColumn();
            searchTableConfigColumn.setTableConfigId(tableConfig.getId());
            List<TableConfigColumn> tableConfigColumnList = tableConfigColumnService.list(searchTableConfigColumn);
            if(CollectionsUtils.isNotEmpty(tableConfigColumnList)){
                resultList = tableConfigColumnList;
            }
        }
        // 如果resultList是空的，则取拉取原数据库字段列表
        if(CollectionsUtils.isEmpty(resultList)
                && StringUtils.isNotBlank(tableConfig.getSourceId())
                && StringUtils.isNotBlank(tableConfig.getTableName())){
            TableInfo tableInfo = sourceService.getTableInfo(tableConfig.getSourceId(), tableConfig.getTableName());
            List<QueryColumn> tableInfoColumnList = tableInfo.getColumns();
            // 转为TableConfigColumn
            if(tableInfoColumnList != null && !tableInfoColumnList.isEmpty()){
                int sort = 30;
                for(QueryColumn queryColumn : tableInfoColumnList){
                    TableConfigColumn tableConfigColumn = new TableConfigColumn();
                    // 为了应对可编辑表格中，没有key会出现各种问题
                    tableConfigColumn.setId(IdGen.uuid());
                    tableConfigColumn.setColumnName(queryColumn.getName());
                    tableConfigColumn.setComment(queryColumn.getComment());
                    tableConfigColumn.setIsShow(Global.YES);
                    tableConfigColumn.setIsQuery(Global.NO);
                    tableConfigColumn.setType(queryColumn.getType());
                    tableConfigColumn.setSort(sort);
                    sort = sort + 30;
                    // 根据数据库字段类型，默认选中不同的查询方式
                    String queryType;
                    String showType;
                    switch (queryColumn.getType()){
                        case QueryColumn.TYPE_VARCHAR:
                        case QueryColumn.TYPE_TEXT:
                            queryType = TableConfigColumn.QUERY_TYPE_LIKE;
                            showType = TableConfigColumn.SHOW_TYPE_STRING_OR_NUMBER;
                            break;
                        case QueryColumn.TYPE_TIMESTAMP:
                            queryType = TableConfigColumn.QUERY_TYPE_DATE_RANGE;
                            showType = TableConfigColumn.SHOW_TYPE_DATE;
                            break;
                        default:
                            queryType = TableConfigColumn.QUERY_TYPE_EQUALS;
                            showType = TableConfigColumn.SHOW_TYPE_STRING_OR_NUMBER;
                            break;
                    }
                    tableConfigColumn.setQueryType(queryType);
                    tableConfigColumn.setShowType(showType);
                    resultList.add(tableConfigColumn);
                }
            }
        }
        result.success(resultList);
        return result;
    }

}
